package com.myblog.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myblog.constant.CodeType;
import com.myblog.constant.RedisHashKey;
import com.myblog.mapper.ArticleMapper;
import com.myblog.mapper.CommentMapper;
import com.myblog.mapper.UserMapper;
import com.myblog.model.Article;
import com.myblog.model.Comment;
import com.myblog.model.Leave;
import com.myblog.model.User;
import com.myblog.service.CommentService;
import com.myblog.service.LikeService;
import com.myblog.service.impl.redis.HashRedisServiceImpl;
import com.myblog.utils.DataMap;
import com.myblog.utils.FileUtilToLocal;
import com.myblog.utils.JsonResult;
import com.myblog.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private HashRedisServiceImpl hashRedisService;

    @Autowired
    private LikeService likeService;

    @Override
    public DataMap getNewCommment(Integer rows, Integer pageNum) {
        PageHelper.startPage(pageNum,rows);
        List<Comment> comments = commentMapper.selectAllCommentOrder();
        PageInfo pageInfo = new PageInfo<>(comments);

        JSONArray jsonArray = new JSONArray();
        for (Comment comment : comments) {
            JSONObject commentJson = new JSONObject();
            commentJson.put("id",comment.getId());
            //获取文章id
            commentJson.put("articleId",comment.getArticleId());
            //获取文章标题
            String articleTitle = articleMapper.selectArticleTitleByArticleId(comment.getArticleId());
            commentJson.put("articleTitle",articleTitle);
            //获取评论内容
            commentJson.put("commentContent",comment.getCommentContent());
            //获取评论时间
            commentJson.put("commentDate",comment.getCommentDate());
            //获取发布评论的人
            String answererName = userMapper.selectUserNameById(comment.getAnswererId());
            commentJson.put("answerer",answererName);

            jsonArray.add(commentJson);
        }

        JSONObject result = new JSONObject();
        result.put("result",jsonArray);

        JSONObject pageJson = new JSONObject();
        pageJson.put("pageNum",pageInfo.getPageNum());
        pageJson.put("pageSize",pageInfo.getSize());
        pageJson.put("total",pageInfo.getTotal());
        pageJson.put("pages",pageInfo.getPages());
        pageJson.put("isFirstPage",pageInfo.isIsFirstPage());
        pageJson.put("isLastPage",pageInfo.isIsLastPage());

        result.put("pageInfo",pageJson);
        return DataMap.success().setData(result);
    }

    @Override
    public DataMap getUserCommment(Integer rows, Integer pageNum, Integer userId) {
        PageHelper.startPage(pageNum,rows);
        List<Comment> comments = commentMapper.selectCommentByRespondentId(userId);
        PageInfo pageInfo = new PageInfo<>(comments);

        JSONArray jsonArray = new JSONArray();
        for (Comment comment : comments) {
            JSONObject commentJson = new JSONObject();
            commentJson.put("id",comment.getId());
            //获取父id
            commentJson.put("pId",comment.getPid());
            //获取文章id
            commentJson.put("articleId",comment.getArticleId());
            //获取文章标题
            String articleTitle = articleMapper.selectArticleTitleByArticleId(comment.getArticleId());
            commentJson.put("articleTitle",articleTitle);
//            //获取评论内容
//            commentJson.put("commentContent",comment.getCommentContent());
            //获取评论时间
            commentJson.put("commentDate",comment.getCommentDate());
            //获取发布评论的人
            String answererName = userMapper.selectUserNameById(comment.getAnswererId());
            commentJson.put("answerer",answererName);
            //获取已读信息
            commentJson.put("isRead",comment.getIsRead());

            jsonArray.add(commentJson);
        }

        JSONObject result = new JSONObject();
        result.put("result",jsonArray);

        JSONObject pageJson = new JSONObject();
        pageJson.put("pageNum",pageInfo.getPageNum());
        pageJson.put("pageSize",pageInfo.getSize());
        pageJson.put("total",pageInfo.getTotal());
        pageJson.put("pages",pageInfo.getPages());
        pageJson.put("isFirstPage",pageInfo.isIsFirstPage());
        pageJson.put("isLastPage",pageInfo.isIsLastPage());

        result.put("pageInfo",pageJson);

        result.put("msgIsNotReadNum",commentMapper.selectNotReadNumByRespondentId(userId));
        return DataMap.success().setData(result);

    }

    @Override
    public DataMap getCommentByArticleId(long articleId,String userName) {
        List<Comment> comments = commentMapper.selectCommentByArticleId(articleId);
        //用于存放result
        JSONArray results = new JSONArray();
        HashMap<Long,List<Comment>> replyMap = new HashMap<>();
        //判断是否为回复评论，实则放入replyMap
        for (Comment comment : comments) {
            if(comment.getPid() != 0 && !replyMap.containsKey(comment.getPid())){
                List<Comment> list = new ArrayList<>();
                list.add(comment);
                replyMap.put(comment.getPid(),list);
            }
            else if(comment.getPid() != 0){
                List<Comment> list = replyMap.get(comment.getPid());
                list.add(comment);
                replyMap.put(comment.getPid(),list);
            }
        }
        //用于存放replies
        for (Comment comment : comments) {
            //根据pid判断评论还是回复评论

            //判断登录用户是否已经点赞过该评论
            if(comment.getPid() == 0){
                int isLiked = 0;
                JSONObject commentJson = new JSONObject();
                //判断登录用户是否已经点赞过该评论
                if (userName != null) {
                    if (likeService.commentIsLike(articleId, (int) comment.getId(), userName)) {
                        isLiked = 1;
                    }
                }
                commentJson.put("isLiked",isLiked);
                //用于存放replies
                List<JSONObject> repliesArray = new ArrayList<>();
                //pid为0，则为评论
                commentJson.put("id",comment.getId());
                commentJson.put("commentContent",comment.getCommentContent());
                commentJson.put("commentDate",comment.getCommentDate());
                String answererName = userMapper.selectUserNameById(comment.getAnswererId());
                //获取用户头像
                String avatarImgUrl = userMapper.selectAvatarImgUrlById(comment.getAnswererId());
                FileUtilToLocal fileUtil = new FileUtilToLocal();
                String useAvatarImgUrl = fileUtil.disposeUserImgUrl(avatarImgUrl);
                commentJson.put("answerer",answererName);
                commentJson.put("avatarImgUrl",useAvatarImgUrl);
                commentJson.put("likes",comment.getLikes());
                //获取本评论的回复
                List<Comment> replies = replyMap.get(comment.getId());
                if(replies == null){
                    commentJson.put("replies",repliesArray);
                }
                else {
                    for (Comment reply : replies) {
                        JSONObject replyJson = new JSONObject();
                        replyJson.put("id", reply.getId());
                        //获取答主信息
                        String answererNameReply = userMapper.selectUserNameById(reply.getAnswererId());
                        replyJson.put("answerer", answererNameReply);
                        //获取回复人信息
                        String respondentName = userMapper.selectUserNameById(reply.getRespondentId());
                        replyJson.put("respondent", respondentName);
                        replyJson.put("commentContent", reply.getCommentContent());
                        replyJson.put("commentDate", reply.getCommentDate());
                        repliesArray.add(replyJson);
                    }
                    commentJson.put("replies",repliesArray);
                }
                results.add(commentJson);
            }
        }

        return DataMap.success().setData(results);
    }

    @Override
    public DataMap publishCommentMessage(String commentContent, long articleId, int answerId) {
        //新建对象将获得的参数传入
        Comment comment =new Comment();
        comment.setArticleId(articleId);
        comment.setCommentContent(commentContent);
        comment.setAnswererId(answerId);
        //发布评论默认pid为0
        comment.setPid(0);
        //发布评论默认respondent=answer
        comment.setRespondentId(answerId);
        //获得发布评论的时间
        TimeUtil timeUtil = new TimeUtil();
        String publishDate = timeUtil.getFormatDateForFive();
        comment.setCommentDate(publishDate);
        //发布评论默认likes = 0
        comment.setLikes(0);
        //发布评论默认未读
        comment.setIsRead((byte) 1);

        commentMapper.addComment(comment);
        //用户总未读信息+1
        hashRedisService.hashIncrement(String.valueOf(answerId), RedisHashKey.ALL_USER_NEWS,1);
        //用户未读评论数量+1
        hashRedisService.hashIncrement(String.valueOf(answerId), RedisHashKey.COMMENT_NEW_NUM,1);
        DataMap flushed = this.getCommentByArticleId(articleId,userMapper.selectUserNameById(answerId));
        return flushed;
    }


    @Override
    public DataMap ReplyComment(String commentContent, long articleId, int answerId, String pIdString, String respondentName) {
        //新建对象将获得的参数传入
        Comment comment =new Comment();
        comment.setArticleId(articleId);
        //处理传过来的评论内容
        if(commentContent.charAt(0) == '@'){
            commentContent =commentContent.substring(respondentName.length()+1,commentContent.length());
        }
        else{
            commentContent =commentContent;
        }
        comment.setCommentContent(commentContent);
        //设置答主id
        comment.setAnswererId(answerId);
        //回复评论默认pid为回复评论的id，pstring格式为p+id，在这里去掉p
        String pIdS = pIdString.substring(1,pIdString.length());
        Integer pId = Integer.parseInt(pIdS);
        comment.setPid(pId);
        //回复评论通过回复人的姓名查找
        Integer respondentId = userMapper.selectUserIdByUsername(respondentName);
        comment.setRespondentId(respondentId);
        //获得回复评论的时间
        TimeUtil timeUtil = new TimeUtil();
        String replyDate = timeUtil.getFormatDateForFive();
        comment.setCommentDate(replyDate);
        //回复评论默认likes = 0
        comment.setLikes(0);
        //回复评论默认未读
        comment.setIsRead((byte) 1);

        commentMapper.addComment(comment);
        //用户总未读信息+1
        hashRedisService.hashIncrement(String.valueOf(answerId), RedisHashKey.ALL_USER_NEWS,1);
        //用户未读评论数量+1
        hashRedisService.hashIncrement(String.valueOf(answerId), RedisHashKey.COMMENT_NEW_NUM,1);

        JSONObject result = new JSONObject();
        String answerName = userMapper.selectUserNameById(answerId);
        result.put("id",comment.getId());
        result.put("answerer",answerName);
        result.put("respondent",respondentName);
        result.put("commentDate",replyDate);
        result.put("commentContent",commentContent);

        return DataMap.success().setData(result);
    }

    @Override
    public DataMap setAllCommentIsRead(Integer respondentId) {
        commentMapper.updateAllCommentIsReadByRespondentId(respondentId);
        return DataMap.success();
    }


}
